package com.emisky.pictures.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.FileItem;

import com.alibaba.fastjson.JSON;
import com.emisky.pictures.common.CommonUtils;
import com.emisky.pictures.common.PictureHelper;
import com.emisky.pictures.common.RequestWrapper;
import com.emisky.pictures.common.exception.PictureException;
import com.emisky.pictures.entity.JsonResultEntity;
import com.emisky.pictures.entity.PictureEntity;
import com.emisky.pictures.entity.PicturePathEntity;
import com.emisky.pictures.entity.PictureSizeEntity;

/**
 * 上传图片Servlet
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private PictureHelper _pictureHelper=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        _pictureHelper=CommonUtils.buildPictureHelper();
    }
    /**
     * 保存图片并获取地址列表
     * @param lstPicturePath
     * @param lstPictureSize
     * @param picture
     */
    private String[] savePicture(
    		List<PicturePathEntity> lstPicturePath,
    		List<PictureSizeEntity> lstPictureSize,
    		PictureEntity picture) throws IOException{
    	
		String[] aryImageUrl=new String[lstPictureSize.size()+1];
		PictureEntity selPicture=this._pictureHelper.getPictureByMd5(picture.getMd5(), picture.getSiteKey());
		if(selPicture==null){
			//如果不存在，才保存到数据库，否则只显示目前的记录
			this._pictureHelper.savePictureFile(lstPicturePath, picture);
			this._pictureHelper.savePicture(picture);
		}else{
			picture=selPicture;
		}
		aryImageUrl[0]=this._pictureHelper.buildImageUrl(lstPicturePath, picture,0,0);
		int sizeIndex=1;
		for (PictureSizeEntity picSize : lstPictureSize) {
			aryImageUrl[sizeIndex]=this._pictureHelper.buildImageUrl(lstPicturePath, picture, picSize.getWidth(), picSize.getHeight());
			sizeIndex++;
		}
		return aryImageUrl;
    }
    /**
     * 构建picture对象
     * @param stream
     * @param fileName
     * @param siteKey
     * @param requestWrapper
     * @return
     * @throws IOException
     */
    private PictureEntity buildPicture(InputStream stream,String fileName,
    		String siteKey,RequestWrapper requestWrapper) throws IOException{
    	long userId=Long.parseLong(requestWrapper.getParameter("userid"));
		String userName=requestWrapper.getParameter("username");
		String clientIp= requestWrapper.getParameter("clientip");
		if(clientIp==null || clientIp==""){
			clientIp=requestWrapper.getIpAddr();
		}
		String suffix=CommonUtils.getSuffix(fileName);
		InputStream imgStream = stream;
		BufferedImage image=ImageIO.read(imgStream);
		ByteArrayOutputStream output=new ByteArrayOutputStream();
		ImageIO.write(image, suffix, output);
		byte[] imageData= output.toByteArray();
		String md5=DigestUtils.md5Hex(imageData);
		PictureEntity picture=new PictureEntity(
								siteKey,
								suffix,
								image.getWidth(),
								image.getHeight(),
								imageData.length,
								userId,
								userName,
								clientIp);
		picture.setMd5(md5);
		picture.setBinaryData(imageData);
		picture.setIsautowidth(Integer.parseInt(requestWrapper.getParameter("autowidth","1")));
		picture.setIscrop(Integer.parseInt(requestWrapper.getParameter("crop","1")));
		picture.setIswatermark(Integer.parseInt(requestWrapper.getParameter("watermark","1")));
		picture.setIsthum(Integer.parseInt(requestWrapper.getParameter("thum","1")));
		return picture;
    }
	/**
	 * 处理上传图片请求
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		RequestWrapper requestWrapper=new RequestWrapper(request);
		JsonResultEntity jsonResult=new JsonResultEntity();
		try {
			//传递的参数
			String siteKey= requestWrapper.getParameter("sitekey");
			
			String[] imageUrls=requestWrapper.getParameterValues("imageurl");
			
			List<PicturePathEntity> lstPicturePath= this._pictureHelper.getPicturePaths(siteKey);
			List<PictureSizeEntity> lstPictureSize= this._pictureHelper.getPictureSizes(siteKey);
			if(requestWrapper.isMultipartContent()){
				//处理表单提交的请求
				Map<String, FileItem> fileParameterMap= requestWrapper.getFileParameterMap();
				for (FileItem fileItem : fileParameterMap.values()) {
					
						PictureEntity picture=this.buildPicture(fileItem.getInputStream(),fileItem.getName(), siteKey,requestWrapper);
						String[] aryImageUrl = this.savePicture(lstPicturePath, lstPictureSize, picture);
						jsonResult.getData().add(aryImageUrl);
				}
			}else if(imageUrls!=null && imageUrls.length>0){
				for (String imageUrl : imageUrls) {
					if(imageUrl.startsWith("http://")){
						//处理携带imageUrl参数
						String referer=requestWrapper.getParameter("referer");
						String[] refInUrl= imageUrl.split("|ref|");
						String realImgUrl=imageUrl;
						if(refInUrl!=null && refInUrl.length>1){
							//处理多imageurl特别指定referer
							if(!CommonUtils.isNullOrEmpty(refInUrl[1])){
								realImgUrl=refInUrl[0];
								referer=refInUrl[1];
							}
						}
						
						byte[] imageData= this._pictureHelper.getHttpPictureData(realImgUrl, referer);
						InputStream imgStream= new ByteArrayInputStream(imageData);
						PictureEntity picture=this.buildPicture(imgStream, realImgUrl, siteKey,requestWrapper);
						String[] aryImageUrl = this.savePicture(lstPicturePath, lstPictureSize, picture);
						jsonResult.getData().add(aryImageUrl);
					}
				}
			}else{
				//处理流传输的单个图片
				String fileName=requestWrapper.getParameter("filename");
				PictureEntity picture=this.buildPicture(request.getInputStream(), fileName, siteKey,requestWrapper);
				String[] aryImageUrl = this.savePicture(lstPicturePath, lstPictureSize, picture);
				jsonResult.getData().add(aryImageUrl);
			}
			jsonResult.setResult(1);
			jsonResult.setMessage("处理图片完成");
		} catch (Exception e) {
			jsonResult.setResult(-1);
			jsonResult.setMessage("处理图片出现异常："+e.getMessage());
		}
		String result=JSON.toJSONString(jsonResult);
		response.setCharacterEncoding("utf-8");        
	    response.setContentType("text/html; charset=utf-8");  
		PrintWriter pw= response.getWriter();
		pw.write(new String(result.toString().getBytes(),"utf-8"));
		pw.flush();
		pw.close();
	}

}
